package com.zzzyh.forumsystemclient.services.impl;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.common.ResultCode;
import com.zzzyh.forumsystemclient.dao.UserMapper;
import com.zzzyh.forumsystemclient.exception.AppException;
import com.zzzyh.forumsystemclient.model.LoginUser;
import com.zzzyh.forumsystemclient.model.Moment;
import com.zzzyh.forumsystemclient.model.User;
import com.zzzyh.forumsystemclient.services.IUserService;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import com.zzzyh.forumsystemclient.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public String login(String username, String password) {
            if( StringUtil.isEmpty(username)
                    || StringUtil.isEmpty(password)) {
                log.warn(ResultCode.FAILED_PARAM_ERROR.getMessage());
                throw new AppException(AppResult.failed(ResultCode.FAILED_PARAM_ERROR));
            }
            UsernamePasswordAuthenticationToken authenticationToken= new UsernamePasswordAuthenticationToken(username,password);
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            if(authentication == null)
                throw new RuntimeException("登录失败");
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            loginUser.getUser().setPassword(null);
            String jsonString = JSON.toJSONString(loginUser);
            return JwtUtils.generateToken(jsonString);
    }

    @Override
    public void register(User user) {
        userMapper.insert(user);
    }

    @Override
    public User getUserinfoByUserId(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public void updateProfile(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Boolean usernameExists(String username, Integer userId) {
        User user = userMapper.selectByUsername(username);
        return user != null && !Objects.equals(user.getId(), userId);
    }

    @Override
    public void updatePassword(String encodedNewPassword, Integer userId) {
        userMapper.updatePassword(encodedNewPassword,userId);
    }

    @Override
    public boolean usernameAndEmailExists(String username, String email) {
        return userMapper.selectByUsernameAndEmail(username,email) != null;
    }

    @Override
    public Integer selectUserIdByUsername(String username) {
        return userMapper.selectUserIdByUsername(username);
    }

    @Override
    public void updateUserIpInfo(User ipUser) {
        userMapper.updateUserIpInfo(ipUser);
    }

    @Override
    public List<Moment> myTalk(Integer userId) {
        return userMapper.myTalk(userId);
    }

    @Override
    public void delMyTalk(Integer talkId) {
        userMapper.delMyTalk(talkId);
    }

    @Override
    public Integer isFollowAuthor(Integer myId, Integer userId) {
        return userMapper.isFollowAuthor(myId, userId);
    }

    @Override
    public void followUser(Integer myId, Integer userId) {
        if (userMapper.isFollowAuthor(myId,userId) ==null){
            userMapper.followUser(myId, userId);
        }else {
            userMapper.updateFollwUser(myId, userId);
        }
    }

    @Override
    public void unFollowUser(Integer myId, Integer userId) {
        userMapper.unFollowUser(myId, userId);
    }

    @Override
    public Integer totalPosts(Integer userId) {
        return userMapper.totalPosts(userId);
    }

    @Override
    public Integer totalLikes(Integer userId) {
        return userMapper.totalLikes(userId);
    }

    @Override
    public Integer totalFollowers(Integer userId) {
        return userMapper.totalFollowers(userId);
    }
}
